let cursorX = 0;
let cursorY = 0;

let $grabbedElement = null;

document.onmousemove = function (event) {
    cursorX = event.pageX;
    cursorY = event.pageY;

    if ($grabbedElement) {
        updateGrabbedPosition();
    }
}

$('.items > .item').mousedown(onItemMouseDown);

async function onItemMouseDown() {
    const $this = $(this);

    if ($grabbedElement && $grabbedElement.data('name') === $this.data('name')) {
        ungrab();
        return;
    }

    if (!$grabbedElement) {
        $grabbedElement = $this;
        updateGrabbedPosition();

        $("<div class='item-placeholder'></div>").insertBefore($this);
        return;
    }

    const craftedElementName = await tryToCraft($grabbedElement, $this);

    if (!craftedElementName)
        return;

    if (!containsElement(craftedElementName)) {
        const newElement$ = $(`<div class="item" data-name="${craftedElementName}"></div>`);

        newElement$.mousedown(onItemMouseDown);
        newElement$.insertBefore($this);
    }

    ungrab();
}

function updateGrabbedPosition() {
    $grabbedElement.addClass('grabbed');
    $grabbedElement.css('top', `${cursorY}px`);
    $grabbedElement.css('left', `${cursorX}px`);
}

function ungrab() {
    $grabbedElement.css('top', '')
    $grabbedElement.css('left', '')
    $grabbedElement.removeClass('grabbed')
    $('.item-placeholder').remove();
    $grabbedElement = null;
}

async function tryToCraft($src, $target) {
    const srcName = $src.data('name');
    const targetName = $target.data('name');

    const response = await fetch(`/Home/TryToCraft?srcName=${srcName}&targetName=${targetName}`);
    return await response.text();
}

function containsElement(name) {
    return $('.item').filter((i, e) => $(e).data("name") === name).length > 0;
}